<?php

namespace App\Dao;

use App\Model\BillsModel;

class BillsDao extends BaseDao
{
    public static function bills_query($params = [])
    {
        $query = BillsModel::query();

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });


        $query->when(checkIsHasField($params,'start_time'),function ($query)use ($params){
            $query->where('created_at','>',$params['start_time']);
        });

        $query->when(checkIsHasField($params,'end_time'),function ($query)use ($params){
            $query->where('created_at','<',$params['end_time']);
        });


        return $query->orderByDesc('created_at');
    }


    //更新用户余额
    public static function moneyUpdate($user_id = 0,$nums = 0,$title = '')
    {
        UsersDao::builder_query([
            'user_id'=>$user_id
        ])->increment('balance',$nums);
        //添加记录
        self::bills_query()->create([
            'user_id'=>$user_id,
            'nums'=>$nums,
            'title'=>$title,
            'balance'=>UsersDao::builder_query([
                'user_id'=>$user_id
            ])->value('balance')
        ]);
    }

    public static function pageinate(array $params)
    {
        return self::bills_query($params)->orderByDesc('created_at')->paginate();
    }

    public static function bills(array $params)
    {
        $query = self::bills_query($params)->orderByDesc('created_at');


        return [
            'list_data'=>$query->get(),
            'zhichu'=>$query->where('nums','<',0)->sum('nums'),
            'shouru'=>$query->where('nums','>',0)->sum('nums')
        ];
    }

    public static function pagenate(array $all)
    {
        return self::bills_query($all)->paginate();
    }

    public static function bills_count(array $params): array
    {
        return [
            'in'=>self::bills_query($params)->where('nums','>',0)->sum('nums'),
            'out'=>self::bills_query($params)->where('nums','<',0)->sum('nums'),
        ];
    }
}
